
document.addEventListener('DOMContentLoaded', function () {
    // 1. 图片上传功能
    const imageUpload = document.getElementById('imageUpload');
    const imageUploadArea = document.getElementById('imageUploadArea');
    const imagePreviewContainer = document.getElementById('imagePreviewContainer');
    const MAX_IMAGES = 5;

    // 点击上传区域触发文件选择
    imageUploadArea.addEventListener('click', function () {
        imageUpload.click();
    });

    // 拖放功能
    imageUploadArea.addEventListener('dragover', function (e) {
        e.preventDefault();
        this.style.borderColor = 'var(--primary-color)';
        this.style.backgroundColor = 'rgba(78, 115, 223, 0.1)';
    });

    imageUploadArea.addEventListener('dragleave', function () {
        this.style.borderColor = '#d1d3e2';
        this.style.backgroundColor = 'transparent';
    });

    imageUploadArea.addEventListener('drop', function (e) {
        e.preventDefault();
        this.style.borderColor = '#d1d3e2';
        this.style.backgroundColor = 'transparent';

        if (e.dataTransfer.files.length > 0) {
            handleImageUpload(e.dataTransfer.files);
        }
    });

    // 文件选择处理
    imageUpload.addEventListener('change', function (e) {
        if (e.target.files.length > 0) {
            handleImageUpload(e.target.files);
        }
    });

    function handleImageUpload(files) {
        const currentImageCount = imagePreviewContainer.children.length;
        const remainingSlots = MAX_IMAGES - currentImageCount;

        if (remainingSlots <= 0) {
            alert(`最多只能上传${MAX_IMAGES}张图片`);
            return;
        }

        const filesToUpload = Array.from(files).slice(0, remainingSlots);

        filesToUpload.forEach(file => {
            if (!file.type.match('image.*')) {
                alert('请选择图片文件！');
                return;
            }

            if (file.size > 5 * 1024 * 1024) {
                alert('图片大小不能超过5MB！');
                return;
            }

            const reader = new FileReader();
            reader.onload = function (event) {
                const imagePreview = document.createElement('div');
                imagePreview.className = 'image-preview-item';
                imagePreview.style.position = 'relative';
                imagePreview.style.display = 'inline-block';

                const img = document.createElement('img');
                img.src = event.target.result;
                img.className = 'image-preview';

                const removeBtn = document.createElement('span');
                removeBtn.className = 'remove-image';
                removeBtn.innerHTML = '&times;';
                removeBtn.addEventListener('click', function () {
                    imagePreview.remove();
                });

                imagePreview.appendChild(img);
                imagePreview.appendChild(removeBtn);
                imagePreviewContainer.appendChild(imagePreview);
            };
            reader.readAsDataURL(file);
        });
    }

    // 2. 字符计数功能
    const itemTitle = document.getElementById('itemTitle');
    const titleCount = document.getElementById('titleCount');
    const itemDescription = document.getElementById('itemDescription');
    const descCount = document.getElementById('descCount');

    itemTitle.addEventListener('input', function () {
        titleCount.textContent = this.value.length;
    });

    itemDescription.addEventListener('input', function () {
        descCount.textContent = this.value.length;
    });

    // 3. 表单验证和提交
    const publishBtn = document.getElementById('publishBtn');

    publishBtn.addEventListener('click', function () {
        // 简单的前端验证
        if (!itemTitle.value.trim()) {
            alert('请填写商品标题');
            itemTitle.focus();
            return;
        }

        if (!itemPrice.value || parseFloat(itemPrice.value) <= 0) {
            alert('请输入有效的商品价格');
            itemPrice.focus();
            return;
        }

        if (imagePreviewContainer.children.length === 0) {
            alert('请至少上传一张商品图片');
            return;
        }

        // 这里实际项目中应该调用API提交表单
        const base64_files = []
        for (let i = 0; i < imagePreviewContainer.children.length; i++) {
            const base64_file = imagePreviewContainer.children[i].querySelector('img').src;
            base64_files.push(base64_file);
        }
        const files = []
        for (let i = 0; i < base64_files.length; i++) {
            const base64 = base64_files[i];
            files.push(base64_to_file(base64));
        }
        publish_product(files);
        // window.location.href = "/my-items";
    });

    // 4. 保存草稿功能
    // document.getElementById('saveDraftBtn').addEventListener('click', function () {
    //     // 这里可以保存到本地存储或调用API保存草稿
    //     alert('草稿已保存');
    // });
});

async function publish_product(files) {
    const name = document.getElementById('itemTitle').value;
    const description = generate_description();
    const price = document.getElementById('itemPrice').value;
    
    const response = await fetch('/api/products', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${localStorage.getItem('token')}`
        },
        body: JSON.stringify({ name, description, price })
    });
    const data = await response.json();
    if (data.status == 'success') {
        const product_id = data.product_id;
        const formData = new FormData();
        for (let i = 0; i < files.length; i++) {
            formData.append('images', files[i]);
        }
        const image_response = await fetch(`/api/product/image/${product_id}`, {
            method: 'POST',
            body: formData
        });
        const image_data = await image_response.json();
        if (image_data.status == 'success') {
            alert('商品发布成功');
            window.location.href = "/profile.html";
        } else {
            const delete_response = await fetch(`/api/products/${product_id}`, {
                method: 'DELETE',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${localStorage.getItem('token')}`
                }
            });
            alert('商品发布失败');
            return;
        }
    } else {
        alert('商品发布失败');
        return;
    }
}

function generate_description() {
    let category = document.getElementById('itemCategory').value;
    if (category)
        category = `类别：${category}\n`
    let condition = document.getElementById('itemCondition').value;
    if (condition)
        condition = `成色：${condition}\n`
    let position = document.getElementById('tradeLocation').value;
    if (position)
        position = `交易地点：${position}\n`
    let tradeFaceToFace = document.getElementById('tradeFaceToFace').checked;
    if (tradeFaceToFace)
        tradeFaceToFace = `交易方式：线下当面交易\n`
    else
        tradeFaceToFace = ''
    let tradeDelivery = document.getElementById('tradeDelivery').checked;
    if (tradeDelivery)
        tradeDelivery = `交易方式：快递邮寄（需协商运费）\n`
    else
        tradeDelivery = ''
    const description = document.getElementById('itemDescription').value;
    const description_text = `${category}${condition}${position}${tradeFaceToFace}${tradeDelivery}${description}`
    return description_text
}

function base64_to_file(base64) {
    const byteString = atob(base64.split(',')[1]);
    const mimeString = base64.split(',')[0].split(':')[1].split(';')[0];
    const ab = new ArrayBuffer(byteString.length);
    const ia = new Uint8Array(ab);
    for (let i = 0; i < byteString.length; i++) {
        ia[i] = byteString.charCodeAt(i);
    }
    return new File([ab], 'image.png', { type: mimeString });
}

